<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-input v-model="queryParams.title" placeholder="请输入文章标题" clearable style="width: 200px;"
                    @keyup.enter.native="handleSearch" />
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">发布文章</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="articleList" style="width: 100%">
            <el-table-column prop="title" label="文章标题">
            </el-table-column>
            <el-table-column prop="categoryId" label="文章分类" width="180">
                <template slot-scope="scope">
                    {{ getCategoryName(scope.row.categoryId) }}
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 40]" :page-size="queryParams.pageSize"
            layout="prev, pager, next" :total="total">
        </el-pagination>

        <!-- 编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="文章标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入文章标题" />
                </el-form-item>
                <el-form-item label="文章分类" prop="categoryId">
                    <el-select v-model="form.categoryId" placeholder="请选择文章分类">
                        <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="文章封面" prop="cover">
                    <my-upload @callParent="handleUploadSuccess" ref="upload" />
                </el-form-item>
                <el-form-item label="文章内容" prop="content">
                    <el-input type="textarea" v-model="form.content" :rows="10" placeholder="请输入文章内容" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { reqArticleList, reqArticleCategoryList, getArticleInfo, getArticleEdit, getArticleDelete, getArticleAdd } from '@/api';
import myUpload from '@/components/upload';

export default {
    name: "Article",
    components: {
        myUpload
    },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 文章列表
            articleList: [],
            // 总条数
            total: 0,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                title: undefined
            },
            // 分类列表
            categoryList: [],
            // 是否显示弹出层
            open: false,
            // 弹出层标题
            title: "",
            // 表单参数
            form: {
                id: undefined,
                title: undefined,
                categoryId: undefined,
                content: undefined,
                cover: undefined
            },
            // 表单校验
            rules: {
                title: [
                    { required: true, message: "文章标题不能为空", trigger: "blur" }
                ],
                categoryId: [
                    { required: true, message: "文章分类不能为空", trigger: "change" }
                ],
                content: [
                    { required: true, message: "文章内容不能为空", trigger: "blur" }
                ],
                cover: [
                    { required: true, message: "文章封面不能为空", trigger: "change" }
                ]
            }
        };
    },
    created() {
        this.getList();
        this.getCategoryList();
    },
    methods: {
        /** 获取分类列表 */
        getCategoryList() {
            reqArticleCategoryList().then(res => {
                this.categoryList = res.rows;
            }).catch(err => {
            })
        },
        /** 根据分类ID获取分类名称 */
        getCategoryName(categoryId) {
            const category = this.categoryList.find(item => item.id === categoryId);
            return category ? category.name : '未分类';
        },
        /** 查询文章列表 */
        getList() {
            this.loading = true;
            reqArticleList({
                pageNum: this.queryParams.pageNum,
                pageSize: this.queryParams.pageSize,
                title: this.queryParams.title,
                isSelf: true
            }).then(res => {
                this.articleList = res.rows;
                this.total = res.total;
                this.loading = false;
            }).catch(err => {
                this.loading = false;
                this.$message.error(err.msg);
            })
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.title = "编辑文章";
            this.open = true;
            this.form = {
                id: row.id,
                title: row.title,
                categoryId: row.categoryId,
                content: row.content,
                cover: row.cover
            };
            // 设置上传组件的图片
            this.$nextTick(() => {
                if (row.cover) {
                    this.$refs.upload.setImgUrl(row.cover);
                }
            });
        },
        /** 取消按钮 */
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 表单重置 */
        reset() {
            this.form = {
                id: undefined,
                title: undefined,
                categoryId: undefined,
                content: undefined,
                cover: undefined
            };
            // 重置上传组件
            this.$nextTick(() => {
                this.$refs.upload.setImgUrl('');
            });
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.title = "发布文章";
            this.$nextTick(() => {
                this.$refs.upload.setImgUrl(null);
            });
            this.open = true;
            this.reset();
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        getArticleEdit(this.form).then(response => {
                            this.$message.success("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        getArticleAdd(this.form).then(response => {
                            this.$message.success("发布成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.$confirm('是否确认删除该文章?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                return getArticleDelete(row.id);
            }).then(() => {
                this.getList();
                this.$message.success("删除成功");
            }).catch(() => { });
        },
        /** 上传成功回调 */
        handleUploadSuccess(url) {
            this.form.cover = url;
        },
        /** 每页条数改变 */
        handleSizeChange(val) {
            this.queryParams.pageSize = val;
            this.getList();
        },
        /** 当前页改变 */
        handleCurrentChange(val) {
            this.queryParams.pageNum = val;
            this.getList();
        },
        /** 搜索按钮操作 */
        handleSearch() {
            this.queryParams.pageNum = 1;
            this.getList();
        }
    }
};
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.mb8 {
    margin-bottom: 8px;
    display: flex;
    justify-content: right;
}

.el-pagination {
    margin-top: 20px;
    text-align: right;
}
</style>